/**
 * @file   1074.cpp
 * @author Shuang Hu <hsmath@ubuntu>
 * @date   Wed Jul 28 19:01:47 2021
 * 
 * @brief  PAT advanced:1074
 * 
 * 
 */
#include<iostream>
#include<vector>
#include<map>
#include<algorithm>
#include<string>
using namespace std;
class Node{
public:
    string nowadd;
    int data;
    string nextadd;
};
class Linkedlist{
private:
    vector<Node> nds;
    vector<Node> list;
    int K;
    int nodenum;
    map<string,int> nodeindex;
    string head;
public:
    Linkedlist();
    void Solve();
    void print();
};
Linkedlist::Linkedlist(){
    cin>>head>>nodenum>>K;
    for(int i=0;i<nodenum;i++){
	Node N;
	cin>>N.nowadd>>N.data>>N.nextadd;
	string tmp=N.nowadd;
	nodeindex[tmp]=i;
	nds.push_back(N);
    }
}
void Linkedlist::Solve(){
    string pos=head;
    while(1){
	if(list.size()%K==0&&list.size()!=0){
	    reverse(list.end()-K,list.end());
	}
	if(pos=="-1"){
	    break;
	}
	else{
	    int index=nodeindex[pos];
	    list.push_back(nds[index]);
	    pos=nds[index].nextadd;
	}
    }
}
void Linkedlist::print(){
    for(int i=0;i<list.size();i++){
	cout<<list[i].nowadd<<" "<<list[i].data;
	if(i==list.size()-1){
	    cout<<" -1"<<endl;
	}else{
	    cout<<" "<<list[i+1].nowadd<<endl;
	}
    }
}
int main(){
    Linkedlist L;
    L.Solve();
    L.print();
}
